package com.engine.wei.base.utils;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.SystemClock;
import android.view.View;

import androidx.annotation.Nullable;

import com.engine.wei.base.R;
import com.engine.wei.base.utils.log.LogUtils;


/**
 * 作者:赵若位
 * 时间:2021/7/27 15:34
 * 功能:关于View的一些常用工具包
 */
public class ViewUtils {

    /*View点击事件间隔*/
    private static final long SINGLECLICKINTERVAL = 800L;

    public static Activity getActivity(View view) {
        if (null != view) {
            Context context = view.getContext();
            while (context instanceof ContextWrapper) {
                if (context instanceof Activity) {
                    return (Activity) context;
                }
                context = ((ContextWrapper) context).getBaseContext();
            }
        }
        return null;
    }

    /**
     * View的单击事件
     *
     * @param view
     * @param interval      过滤点击事件执行的周期
     * @param isSingleClick true，表示该控件和同一个 Activity 中其他控件共用一个上次单击时间，也可以手动改成 false，表示该控件自己独享一个上次单击时间
     * @param listener
     */
    private static void singleClick(View view, long interval,
                                    boolean isSingleClick, View.OnClickListener listener) {
        if (null == view || null == listener) {
            return;
        }
        View target = (isSingleClick && null != getActivity(view)) ? getActivity(view).getWindow().getDecorView() : view;
        Object obj = target.getTag(R.id.single_click_tag_last_single_click_millis);
        long millis = obj instanceof Long ? (long) obj : 0L;
        if (SystemClock.uptimeMillis() - millis >= interval) {
            target.setTag(R.id.single_click_tag_last_single_click_millis, SystemClock.uptimeMillis());
            listener.onClick(view);
        } else {
            LogUtils.e("点击时间间隔太短");
        }
    }

    //单击事件过滤
    private static void singleClick(@Nullable View view, View.OnClickListener listener) {
        singleClick(view, SINGLECLICKINTERVAL, true, listener);
    }

    //单击事件过滤
    public static void setSingleClickListener(View view, long interval,
                                              boolean isSingleClick, View.OnClickListener listener) {
        if (null != view && null != listener) {
            view.setOnClickListener(v -> singleClick(view, interval, isSingleClick, listener));
        }
    }

    public static void setSingleClickListener(View view, View.OnClickListener listener) {
        if (null != view && null != listener) {
            view.setOnClickListener(v -> singleClick(view, listener));
        }
    }


}
